package com.shengzai.sql

import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.{DataFrame, SparkSession}

object Demo6UDF {

  def main(args: Array[String]): Unit = {

    val spark: SparkSession = SparkSession
      .builder()
      .master("local")
      .appName("hive")
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()
    import spark.implicits._
    import org.apache.spark.sql.functions._


    val studentDF: DataFrame = spark
      .read
      .format("csv")
      .option("sep", ",")
      .schema("id STRING,name STRING, age INT,sex STRING,clazz STRING")
      .load("data/students.txt")

    // 定义UDF函数，里面是一个lambda表达式

    val myUDF: UserDefinedFunction = udf((line: String) => {
      line.substring(0, 2)
    })

    studentDF.select(myUDF($"clazz") as "udf").show()

    /**
     * 在 SparkSQL中使用
     */

    studentDF.createOrReplaceTempView("student")

    //注册sql使用的自定义函数
    spark.udf.register("subClazz", myUDF)

    spark.sql(
      """
        |select
        |subClazz(clazz)
        |from
        |student
        |""".stripMargin).show()




  }

}
